package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;

import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/checkitem")
public class CheckItemController {
    @Reference//查找服务
    private CheckItemService checkItemService;

    //    新增检查项
    @PreAuthorize("hasAuthority('CHECKITEM_ADD')")//权限校验
    @RequestMapping(value = "/add")
    public Result add(@RequestBody CheckItem checkItem) {
        try {
            checkItemService.add(checkItem);
        } catch (Exception e) {
            e.printStackTrace();
            //return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL);
            return new Result(false);
        }

        //return new Result(false, MessageConstant.ADD_CHECKGROUP_SUCCESS);
        return new Result();
    }

    //    分页查询
    @PreAuthorize("hasAnyAuthority('CHECKITEM_QUERY')")//权限校验
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResults = checkItemService.pageQuery(queryPageBean);

        return pageResults;
    }

    //删除
    @PreAuthorize("hasAuthority('CHECKITEM_DELETE')")//权限校验
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        //优化到service层判断是否有中间表，如果存在提示
        // try {
        return checkItemService.deleteById(id);

       /* } catch (Exception e) {
            e.printStackTrace();
            return new Result(false);
        }*/

    }

    //数据回显
    @PreAuthorize("hasAuthority('CHECKITEM_EDIT')")//权限校验
    @RequestMapping("/edit")
    public Result edit(@RequestBody CheckItem checkItem) {
        try {
            checkItemService.edit(checkItem);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false);
        }
        return new Result();
    }

    //编辑之前根据id查询数据库
    @RequestMapping("/finById")
    public Result finById(Integer id) {
        try {
            CheckItem checkItem = checkItemService.finById(id);
            return new Result(checkItem);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false);
        }

    }

    //查询全部检查相信息
    @RequestMapping("/findAll")
    public Result findAll() {
        List<CheckItem> checkItemList = checkItemService.findAll();
        if (checkItemList != null && checkItemList.size() > 0) {
            Result result = new Result(checkItemList);
            result.setData(checkItemList);
            return result;
        }
        return new Result(false);
    }
//    根据项目名模糊查询

}
